/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import beans.Barrio;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

/**
 *
 * @author Guido Cresta
 */
public class BarrioDao {

    private static List<Barrio> barrios = null;

    public static List<Barrio> getBarrios() {
        if (barrios == null) {
            Session session = SimpleSessionFactory.getSessionFactory(null).openSession();
            Query q = session.createQuery("from beans.Barrio");

            barrios = q.list();

            session.close();
        }
        return barrios;
    }

    public static Barrio getBarrioPorNombre(String nombre){
        if(barrios == null)
            getBarrios();

        for(Barrio barrio : barrios){
            if(barrio.getNombre().compareTo(nombre)==0)
                return barrio;
        }

        return null;
    }

    public static boolean saveOrUpdate(Barrio barrio){
        SessionFactory sf = null;
        Session session = null;
        try{
            sf = SimpleSessionFactory.getSessionFactory(null);
            session = sf.openSession();
            session.beginTransaction();

            session.saveOrUpdate(barrio);
            session.getTransaction().commit();

            return true;//Exito!
        }catch(Exception ex){
            if(session != null && session.isOpen())
                session.getTransaction().rollback();

            return false;//Fallido
        }finally{
            session.close();
        }
    }

    public static boolean saveOrUpdateOrDelete(List<Barrio> barrios, List<Barrio> barriosABorrar) {
        SessionFactory sf = null;
        Session session = null;
        try{
            sf = SimpleSessionFactory.getSessionFactory(null);
            session = sf.openSession();
            session.beginTransaction();

            for(Barrio barrio : barrios)
                session.saveOrUpdate(barrio);

            for(Barrio barrio : barriosABorrar)
                session.delete(barrio);

            session.getTransaction().commit();

            return true;//Exito!
        }catch(Exception ex){
            if(session != null && session.isOpen())
                session.getTransaction().rollback();

            ex.printStackTrace();
            return false;//Fallido
        }finally{
            session.close();
        }
    }

}
